package com.chinafree.auth.service.impl;

import com.chinafree.auth.model.bo.LoginUserBo;
import com.chinafree.auth.model.param.RegistrationParam;
import com.chinafree.auth.service.ForgetPasswordService;
import com.chinafree.auth.service.LoginUserService;
import com.chinafree.auth.service.VerificationCode;
import com.chinafree.common.model.enumeration.ResponseCodeEnum;
import com.chinafree.common.model.response.BaseResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;


/**
 * 忘记密码
 */
@Service
public class ForgetPasswordServiceImpl implements ForgetPasswordService {

    @Autowired
    private VerificationCode verificationCode;

    @Autowired
    private LoginUserService loginUserService;

    private final String FORGET_PASSWORD = "FORGET_PASSWORD_";

    @Override
    public BaseResponse sendRegisterVerificationCode(String phoneNumber) {
        return verificationCode.sendRegisterVerificationCode(FORGET_PASSWORD, phoneNumber);
    }

    @Override
    public BaseResponse resetPassword(RegistrationParam registrationParam) {
        String phoneNumber = registrationParam.getPhoneNumber();
        String verification = registrationParam.getVerification();
        String password = registrationParam.getPassword();
        if (StringUtils.isEmpty(phoneNumber)) {
            return new BaseResponse(ResponseCodeEnum.FORBIDDEN, "没有填写手机号");
        }
        if (StringUtils.isEmpty(verification)) {
            new BaseResponse(ResponseCodeEnum.FORBIDDEN, "没有填写验证码");
        }
        if (StringUtils.isEmpty(password)) {
            new BaseResponse(ResponseCodeEnum.FORBIDDEN, "没有填写密码");
        }
        String msg = verificationCode.checkVerificationCode(FORGET_PASSWORD, phoneNumber, verification);
        if(msg!=null){
            return new BaseResponse(ResponseCodeEnum.FORBIDDEN, msg);
        }
        Optional<LoginUserBo> loginUserByLoginMobile1 = loginUserService.getLoginUserByLoginMobile(phoneNumber);
        if (!loginUserByLoginMobile1.isPresent()) {
            return new BaseResponse(ResponseCodeEnum.FORBIDDEN, "手机号未注册");
        }
        Long id = loginUserByLoginMobile1.get().getId();
        Optional<LoginUserBo> loginUserBo = loginUserService.modifyPasswordById(id, password);
        if (!loginUserBo.isPresent()) {
            return new BaseResponse(ResponseCodeEnum.FORBIDDEN, "密码未更新成功");
        }
        return new BaseResponse(ResponseCodeEnum.SUCCESS, "更新成功");
    }
}
